package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.entity.SmsSend;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.service.impl.SmsSendServiceImpl;
import com.sanerzone.smscenter.biz.utils.TableNameHelper;
import com.sanerzone.smscenter.biz.utils.UnicodeUtil;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.common.tools.SpringContextHelper;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 得力数据
 * 可批量发送
 */
public class SmsApiDLSJv2 extends GateWayHttpAbstract
{

    public SmsApiDLSJv2(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    private static SmsSendServiceImpl smsSendService = SpringContextHelper.getBean(SmsSendServiceImpl.class);

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        params.put("account", paramsMaps.get("account"));
        params.put("sign", DigestUtils.md5Hex(DigestUtils.md5Hex(paramsMaps.get("passwd"))  + mt.getId() + paramsMaps.get("apiKey")).toUpperCase());
        params.put("content", mt.getSmsContent());
        params.put("mobile", mt.getPhone());
        params.put("templet_type",  paramsMaps.get("templet_type"));//0：通知类，1：验证类，2：营销类
        params.put("user_ordernum", mt.getId());
        params.put("extend",  paramsMaps.get("extend"));
        String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/Api/Order/send", Joiner.on("&").withKeyValueSeparator("=").join(params), null);

        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);

        List<SMSSRMessage> resultList = Lists.newArrayList();

        SMSSRMessage message = initGatewayResultMessage(json, mt, "code");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        JSONObject object = JSON.parseObject(json);
        if(StringUtils.equals(message.getResult(), "F10199")) {
            resultCode = String.valueOf(object.getString("code"));
            resultMessage = String.valueOf(UnicodeUtil.decode(object.getString("msg")));
            if(StringUtils.equals(resultCode, "2000")) {
                taskid = mt.getId();
            }
            message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "2000");
            resultList.add(message);
        }
        return resultList;
    }

    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        logger.info("{}网关推送状态报告:{}", gateWayID, text);
        if (StringUtils.isNotBlank(text)) {
            JSONObject object = JSON.parseObject(text);
            SMSRTMessage smsRtMessage = initSmsRtMessage(String.valueOf(object.getString("user_ordernum")), object.getString("mobile"), object.getString("mobile"),
                    String.valueOf(object.getString("status")), "2");
            rtList.add(smsRtMessage);
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        logger.info("{}网关推送用户上行:{}", gateWayID, text);
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("1");
        JSONObject object = JSON.parseObject(text);
        SMSMOMessage sMSMOMessage = new SMSMOMessage();
        sMSMOMessage.setGateWayID(gateWayID);
        sMSMOMessage.setMsgContent(UnicodeUtil.decode(object.getString("content")));
//                sMSMOMessage.setMsgid(object.valueOf(root.element("MsgId").getStringValue()));
        sMSMOMessage.setPhone(object.getString("mobile"));
        sMSMOMessage.setSenttime(object.getString(""));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
        sMSMOMessage.setUuid(UUID.randomUUID().toString());
        moList.add(sMSMOMessage);
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("sendStatus","T000");
        map.put("gatewayStatus","P100");
        map.put("gatewayId",this.gateWayID);
        map.put("tableName","sms_send_" + TableNameHelper.getTableIndex(new Date()));
        map.put("orderby","create_time");
        List<SmsSend> list = smsSendService.findList(map);
        if (null != list && list.size() > 0) {
            for (SmsSend send : list) {
                Map<String, String> params = Maps.newHashMap();
                params.put("account",paramsMaps.get("account"));
                params.put("user_ordernum",send.getId());
                params.put("sign",DigestUtils.md5Hex(DigestUtils.md5Hex(paramsMaps.get("passwd")) + send.getId() + paramsMaps.get("apiKey") ));
                String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/Api/Order/order_search", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
                if (StringUtils.isNotBlank(json)) {
                    JSONObject object = JSON.parseObject(json);
                    if (StringUtils.equals("2000", object.getString("code"))) {

                    }
                }
            }
        }
//        params.put("sign", DigestUtils.md5Hex(DigestUtils.md5Hex(paramsMaps.get("passwd")) + paramsMaps.get("templetid") + mt.getId() + paramsMaps.get("apiKey")).toUpperCase());

        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }

    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("account",paramsMaps.get("account"));
        params.put("sign", DigestUtils.md5Hex(DigestUtils.md5Hex(paramsMaps.get("passwd")) + paramsMaps.get("apiKey")).toUpperCase());
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/Api/Order/balance_search" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        JSONObject object = JSON.parseObject(result);
        if (StringUtils.equals("2000",object.get("code").toString())) {
            return "余额：" + object.getString("balance");
        }
        return "余额查询失败";
    }

    public static void main(String[] args)
    {
        String params = "{\"account\":\"hzfansheng\",\"passwd\":\"123456\",\"apiKey\":\"fansheng888\",\"templetid\":\"10118\",\"param\":\"1234,5\",\"apiUrl\":\"http://119.147.44.183/index.php/\"}";
        SmsApiDLSJv2 api = new SmsApiDLSJv2("ZY",params);
        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setId("test123456");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
    }

}